package com.cg.springSecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cg.springSecurity.mapper.UserMapper;
import com.cg.springSecurity.pojo.User;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws BadCredentialsException {

        //todo 加入登录参数验证逻辑
//        if(user == null){//数据库没有数据，认证失败
//            throw new BadCredentialsException("用户名不存在！");
//        }
        //调用usersMapper方法，根据用户名查询数据库
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.setRoles(userMapper.getUserRolesByRole(user.getRole()));
		//手动设置了role，也可以通过数据库查询获取
//        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");  //配置角色

        return user;
    }

}
